interface IMemo {
  text: string;
  completed: boolean;
}

let obj: IMemo[] = JSON.parse(localStorage.getItem("Memo")) || [
  { text: "第三方斯蒂芬", completed: false },
  { text: "大范甘迪发广告", completed: false },
  { text: "电饭锅回复", completed: true },
];

function save(): void {
  localStorage.setItem("Memo", JSON.stringify(obj));
}

function load(): void {
  btn("all");
}

// 新增
document
  .querySelector("#add")
  ?.addEventListener("click", function addMemo(): void {
    const input: HTMLInputElement | null = document.querySelector("#MemoInput");
    const MemoValue: string = input?.value ?? "";
    if (MemoValue) {
      obj.push({
        text: MemoValue,
        completed: false,
      });
      // 清空输入框
      input?.value = "";
      // 保存更新后的任务列表
      save();
      // 刷新显示所有任务
      btn("all");
    } else {
      alert("请输入任务内容");
    }
  });

// 切换对应数据的状态
function updateCompletion(MemoId: number): void {
  const Memo: IMemo | undefined = obj[MemoId];
  if (Memo) {
    Memo.completed = !Memo.completed;
    save();
    btn("all");
  }
}

// 从 obj 数组中删除对应的数据
function deleteMemo(MemoId: number): void {
  if (MemoId >= 0 && MemoId < obj.length) {
    obj.splice(MemoId, 1);
    save();
    btn("all");
  }
}

function btn(filter: "all" | "incomplete" | "completed"): void {
  // 获取任务列表
  const List: HTMLUListElement | null = document.querySelector("#List");
  // 清空任务列表
  List?.innerHTML = "";
  // 初始化一个变量，用来计数
  let num: number = 0;
  // Memo 是当前遍历到的任务对象，i 是任务在数组中的索引。
  obj.forEach((Memo, i) => {
    // 根据 filter 判断显示哪一个
    if (
      filter === "all" ||
      (filter === "incomplete" && !Memo.completed) ||
      (filter === "completed" && Memo.completed)
    ) {
      // 改变复选框状态
      const completed: string = Memo.completed ? "checked" : "";
      // 添加任务列表内容
      List?.innerHTML += `
            <li id='li${i}'>
                <input type="checkbox" id='checkbox${i}' ${completed} onclick="updateCompletion(${i})">
                <label for='checkbox${i}' class="${
        Memo.completed ? "completed" : ""
      }">${Memo.text}</label>
                <button class="delete-btn" onclick="deleteMemo(${i})">删除</button>
            </li>
        `;
    }
    // 如果没有选中复选框，未完成任务+1
    if (!Memo.completed) {
      num++;
    }
  });
  // 未完成任务的个数
  document.getElementById("incomplete")?.textContent = "未完成任务: " + num;
}

window.onload = load;
